package com.situ.library;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.situ.JDBC.JDBCUtil;


public class BookDao {
	/**
	 * 执行insert-sql插入一条记录
	 * 
	 * @param model
	 * @return
	 * @throws SQLException
	 */
	public int insert(BookModel book) {// add save 面向对象的开发
		String sql = "insert into book(b_id,b_name,number,count)values(?,?,?,?)";
		Connection conn = null;
		conn = JDBCUtil.getConnection();
		PreparedStatement ps = null;
		if (conn == null)
			return 0;
		try {
			ps = conn.prepareStatement(sql);
			ps.setString(1, book.getId());
			ps.setString(2, book.getName());
			ps.setInt(3, book.getNumber());
			ps.setInt(4, book.getCount());
			return ps.executeUpdate(); // 执行sql语句，并返回影响的行数
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JDBCUtil.close(conn, ps);
		}
		return 0;

	}

	/**
	 * 根据逻辑主键删除记录
	 * 
	 * @param model
	 * @return
	 */
	public int deleteByCode(BookModel book) {
		String sql = "delete from book where b_id = ?";
		Connection conn = JDBCUtil.getConnection();
		if (conn == null)
			return 0;
		PreparedStatement ps = null;
		try {
			ps = conn.prepareStatement(sql);
			ps.setString(1, book.getId());
			return ps.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JDBCUtil.close(conn, ps);
		}
		return 0;
	}

	/**
	 * 根据逻辑主键修改记录其他全部字段
	 * 
	 * @param model
	 * @return
	 */
	public int update(BookModel book) {
		String sql = "update book set b_name=?,number=?,count=? where b_id=?";
		Connection conn = JDBCUtil.getConnection();
		if (conn == null)
			return 0;
		PreparedStatement ps = null;
		try {
			ps = conn.prepareStatement(sql);
			ps.setString(1, book.getName());
			ps.setInt(2, book.getNumber());
			ps.setInt(3, book.getCount());
			ps.setString(4, book.getId());
			return ps.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JDBCUtil.close(conn, ps);
		}
		return 0;
	}

	/**
	 * 根据多个查询条件 - 执行查询sql，返回结果构成的实体类集合
	 * 
	 */
	public List<BookModel> selectOrderList(BookModel book) {
		// 要进行字符串拼接，使用StringBuffer/StringBuilder
		StringBuffer sql = new StringBuffer("select b_id,b_name,number,count from book order by count desc");
		Connection conn = JDBCUtil.getConnection();
		if (conn == null)
			return null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		List<BookModel> list = new ArrayList<>();
		try {
			ps = conn.prepareStatement(sql.toString());
			rs = ps.executeQuery();
			BookModel b = null;
			while (rs.next()) {// ORM（把数据库的表的信息转换成数据库的过程）
				b = new BookModel(null, null, null, null);
				b.setId(rs.getString("b_id"));
				b.setName(rs.getString("b_name"));
				b.setNumber(rs.getInt("number"));
				b.setCount(rs.getInt("count"));
				list.add(b);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JDBCUtil.close(conn, ps, rs);
		}
		return list;
	}

	/**
	 * 根据多个查询条件 - 执行查询sql，返回结果构成的实体类集合
	 * 
	 */
	public List<BookModel> selectList(BookModel book) {
		// 要进行字符串拼接，使用StringBuffer/StringBuilder
		StringBuffer sql = new StringBuffer("select b_id,b_name,number,count from book ");
		List<Object> vals = appendWhere(sql, book);
		Connection conn = JDBCUtil.getConnection();
		if (conn == null)
			return null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		List<BookModel> list = new ArrayList<>();
		try {
			ps = conn.prepareStatement(sql.toString());
			for (int i = 0; i < vals.size(); i++)
				ps.setObject(i + 1, vals.get(i));
			rs = ps.executeQuery();
			BookModel b = null;
			while (rs.next()) {// ORM（把数据库的表的信息转换成数据库的过程）
				b = new BookModel(null, null, null, null);
				b.setId(rs.getString("b_id"));
				b.setName(rs.getString("b_name"));
				b.setNumber(rs.getInt("number"));
				b.setCount(rs.getInt("count"));
				list.add(b);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JDBCUtil.close(conn, ps, rs);
		}
		return list;
	}

	private List<Object> appendWhere(StringBuffer sql, BookModel book) {
		sql.append(" where 1=1 ");
		List<Object> vals = new ArrayList<>();
		String Id = book.getId();
		if (Id != null && !Id.trim().isEmpty()) { // !code.trim().isEmpty()：不是空字符串（即空格一类的）
			sql.append(" and b_id = ? ");
			vals.add(Id.trim());
		}
		String name = book.getName();
		if (name != null && !name.trim().isEmpty()) {
			sql.append(" and b_name = ? ");
			vals.add(name.trim());
		}
		Integer number = book.getNumber();
		if (number != null) {
			sql.append(" and number = ? ");
			vals.add(number);
		}
		Integer count = book.getCount();
		if (count != null) {
			sql.append(" and count = ? ");
			vals.add(count);
		}
		return vals;
	}
}
